<template>
  <div id="assets-library-object3dcustom">
    <!-- <n-alert type="info" :bordered="false" closable class="mb-2 mx-2">
      {{ "拖拽或双击添加至场景中" }}
    </n-alert> -->

    <div class="list">
      <!-- 新建文件夹 -->
      <div
        class="create-new-folder px-10px pb-10px text-13px color-#4583ff flex items-center"
        @click="dialogVisible = true"
      >
        <el-icon size="14" color="#4583ff"><Plus /></el-icon>
        <span class="m-l-10px">新建文件夹</span>
      </div>

      <!-- 文件夹列表 -->
      <div class="folder-list">
        <div class="folder" v-for="folder in folderStructure" :key="folder.id">
          <div
            class="file-name flex items-center p-10px hover-container cursor-pointer text-13px"
          >
            <div
              class="flex-1 flex-inline items-center color-#333"
              @click="toggleFolder(folder.id)"
            >
              <!-- 折叠展开 -->
              <el-icon class="mr-5px" size="14" color="#333333">
                <ArrowDown v-if="folder.expanded" />
                <ArrowRight v-else />
              </el-icon>

              <span>{{ folder.name }}</span>
            </div>
            <div class="operation-buttons">
              <!-- 添加按钮 -->
              <el-icon
                size="14"
                color="#4583ff"
                @click="handleAddButtonClick(folder.id)"
              >
                <CirclePlus />
              </el-icon>
              <!-- 修改按钮 -->
              <el-icon
                size="14"
                color="#4583ff"
                @click="handleEditButtonClick(folder.id)"
              >
                <Edit />
              </el-icon>
              <!-- 删除按钮 -->
              <el-icon
                size="14"
                color="#4583ff"
                @click="handleDeleteButtonClick(folder.id)"
              >
                <Delete />
              </el-icon>
            </div>
          </div>
          <div v-if="folder.expanded" class="folder-content">
            <!-- 有模型文件 -->
            <template v-if="folder.models.length > 0">
              <div class="cards">
                <n-card
                  size="small"
                  hoverable
                  v-for="item in folder.models"
                  :key="item.id"
                  @dblclick="addCustomToScene(item)"
                  draggable="true"
                  @dragstart="dragCustomStart($event, item)"
                  @dragend="dragCustomEnd"
                  @contextmenu="handleContextmenu($event, folder, item)"
                >
                  <template #cover>
                    <img
                      :src="item.preview"
                      :alt="item.name"
                      draggable="false"
                    />
                  </template>
                  <n-tooltip placement="bottom" trigger="hover">
                    <template #trigger> {{ item.name }}</template>
                    <span> {{ item.name }} </span>
                  </n-tooltip>
                </n-card>
              </div>
            </template>
            <!-- 无模型文件 -->
            <template v-else>
              <div class="empty-folder flex justify-center">
                <el-empty :image-size="62" description="暂无模型" />
              </div>
            </template>
          </div>
        </div>
      </div>
    </div>
  </div>

  <EsContextmenu
    ref="contextmenuRef"
    placement="right-start"
    trigger="manual"
    size="small"
    :options="contextmenuOptions"
    @select="handleContextmenuSelect"
  />

  <!-- 新建文件夹的弹窗 -->
  <el-dialog
    append-to-body
    draggable
    title="文件夹"
    v-model="dialogVisible"
    width="450px"
    :before-close="handleClose"
  >
    <div>
      <el-form ref="formRef" :model="form" :rules="rule" label-width="60px">
        <el-form-item label="名称" prop="filename">
          <el-input v-model="form.filename" placeholder="请输入文件夹名称" />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="loading" @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleConfirm">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>

  <!--上传模型弹窗 -->
  <el-dialog
    title="上传模型"
    draggable
    append-to-body
    v-model="uploadDialogVisible"
    width="820px"
    min-height="380px"
    :before-close="handleUploadClose"
  >
    <div
      v-if="uploadDialogVisible"
      class="upload-dialog-content flex justify-between gap-24px w-full"
    >
      <div class="form-view min-w-0">
        <el-form
          ref="uploadFormRef"
          :model="uploadForm"
          :rules="uploadRule"
          label-width="100px"
        >
          <el-form-item label="文件夹" prop="folderId">
            <el-select v-model="uploadForm.folderId" placeholder="请选择文件夹">
              <el-option
                v-for="folder in folderStructure"
                :key="folder.id"
                :label="folder.name"
                :value="folder.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="uploadForm.name" placeholder="请输入模型名称" />
          </el-form-item>
          <el-form-item label="预览图">
            <el-upload
              class="upload-preview flex-inline items-center justify-center"
              action="#"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handlePreviewChange"
            >
              <img v-if="previewUrl" :src="previewUrl" class="preview-image" />
              <el-icon v-else class="upload-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="模型" prop="model">
            <el-upload
              v-model:file-list="modelFile"
              class="upload-model"
              ref="uploadModelRef"
              action="#"
              :auto-upload="false"
              :limit="1"
              :on-change="handleModelChange"
              :on-remove="handleModelRemove"
              :on-exceed="handleExceed"
              accept=".gltf,.glb,.fbx,.obj"
            >
              <template #trigger>
                <el-button type="primary">选择文件</el-button>
              </template>
              <template #tip>
                <div class="el-upload__tip">
                  支持 .gltf/.glb/.fbx/.obj 格式文件
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <div class="preview-view min-w-0">
        <div
          id="preview-container"
          class="preview-container h-327px w-327px border border-dashed border-#d9d9d9 rounded-4px"
          ref="previewRef"
        ></div>
      </div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="loading" @click="handleUploadClose"
          >取消</el-button
        >
        <el-button
          :loading="loading"
          type="primary"
          @click="handleUploadConfirm"
          >确认</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  ElIcon,
  ElDialog,
  ElInput,
  ElButton,
  ElForm,
  ElFormItem,
  ElUpload,
  ElSelect,
  ElOption,
  ElMessage,
  ElMessageBox,
  ElEmpty,
  ElLoading,
} from "element-plus";
import { ref, toRaw, onMounted, nextTick, unref, markRaw } from "vue";
import {
  Plus,
  CirclePlus,
  Edit,
  Delete,
  ArrowDown,
  ArrowRight,
} from "@element-plus/icons-vue";
import EsContextmenu from "@/components/es/EsContextmenu.vue";
import { CustomObject3D } from "@/core/objects/customObject3D";
import { useDragStore } from "@/store/modules/drag";
import { screenToWorld } from "@/utils/common/scenes";
import { Storage } from "@/core/Storage";
import { Viewport } from "@/core/uploadPreview/Viewport";
import { EditorPreview } from "@/core/uploadPreview/EditorPreview";
import { LoaderPreview } from "@/core/uploadPreview/LoaderPreview";
import { getViewportImage } from "@/utils/common/scenes";
import { useDispatchSignal } from "@/hooks/useSignal";

const dbStorage = new Storage();

const formRef = ref(null);

const form = ref({
  filename: "",
});
const rule = ref({
  filename: [{ required: true, message: "请输入文件夹名称", trigger: "blur" }],
});
const dialogVisible = ref(false);

const loading = ref(false);

// 存储文件夹结构的数据
const folderStructure = ref([]);

// 初始化时加载已保存的文件夹结构
const initFolderStructure = async () => {
  try {
    const savedStructure = await dbStorage.getOtherItem("folderStructure");
    if (savedStructure) {
      folderStructure.value = savedStructure;
    }
  } catch (error) {
    console.error("加载文件夹结构失败:", error);
  }
};

// 编辑相关的响应式变量
const isEdit = ref(false);
const editingFolderId = ref("");

// 编辑按钮点击处理
const handleEditButtonClick = (folderId) => {
  const folder = folderStructure.value.find((f) => f.id === folderId);
  if (folder) {
    isEdit.value = true;
    editingFolderId.value = folderId;
    form.value.filename = folder.name;
    dialogVisible.value = true;
  }
};

// 删除按钮点击处理
const handleDeleteButtonClick = async (folderId) => {
  try {
    await ElMessageBox.confirm(
      "确定要删除该文件夹吗？删除后将无法恢复",
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    loading.value = true;

    // 过滤掉要删除的文件夹
    const updatedStructure = folderStructure.value.filter(
      (f) => f.id !== folderId
    );

    // 使用纯 JavaScript 对象，避免 Vue 响应式包装
    const plainData = JSON.parse(JSON.stringify(updatedStructure));

    // 更新本地状态
    folderStructure.value = plainData;
    // 存储纯数据对象
    await dbStorage.setOtherItem("folderStructure", plainData);

    ElMessage.success("删除成功");
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除文件夹失败:", error);
      ElMessage.error("删除失败");
    }
  } finally {
    loading.value = false;
  }
};

// 确认添加文件夹
const handleConfirm = async () => {
  if (!formRef.value) return;

  try {
    loading.value = true;
    const valid = await formRef.value.validate();
    if (valid) {
      if (isEdit.value) {
        // 编辑模式
        const folder = folderStructure.value.find(
          (f) => f.id === editingFolderId.value
        );
        if (folder) {
          folder.name = form.value.filename;
          // 使用纯 JavaScript 对象，避免 Vue 响应式包装
          const plainData = JSON.parse(JSON.stringify(folderStructure.value));

          // 更新本地状态
          folderStructure.value = plainData;
          // 存储纯数据对象
          await dbStorage.setOtherItem("folderStructure", plainData);

          ElMessage.success("修改成功");
        }
      } else {
        // 新建模式
        const newFolder = {
          id: Date.now().toString(),
          name: form.value.filename,
          type: "folder",
          children: [],
          models: [],
        };

        // 使用纯 JavaScript 对象，避免 Vue 响应式包装
        const plainData = JSON.parse(
          JSON.stringify([...folderStructure.value, newFolder])
        );

        // 更新本地状态
        folderStructure.value = plainData;
        // 存储纯数据对象
        await dbStorage.setOtherItem("folderStructure", plainData);

        ElMessage.success("创建成功");
      }

      dialogVisible.value = false;
      form.value.filename = "";
      isEdit.value = false;
      editingFolderId.value = "";
    }
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  } finally {
    loading.value = false;
  }
};

// 修改 handleClose 函数
const handleClose = () => {
  formRef.value?.resetFields();
  formRef.value?.clearValidate();
  dialogVisible.value = false;
  isEdit.value = false;
  editingFolderId.value = "";
};

// 在组件挂载时加载文件夹结构
onMounted(() => {
  initFolderStructure();
});

// 展开/折叠文件夹
const toggleFolder = (folderId) => {
  const folder = folderStructure.value.find((f) => f.id === folderId);
  if (folder) {
    folder.expanded = !folder.expanded;
  }
};

const handleAddButtonClick = (folderId) => {
  uploadDialogVisible.value = true;
  uploadForm.value.folderId = folderId;
};

// 上传模型相关
const uploadDialogVisible = ref(false);
const uploadFormRef = ref(null);
const previewUrl = ref("");
const modelFile = ref([]);
const uploadModelRef = ref(null);

//模型预览
const previewRef = ref(null);
let modelViewer = null;
let previewEditor = null;
let previewLoader = null;
const modelLoading = ref(false);

const uploadForm = ref({
  folderId: "",
  id: "",
  name: "",
  preview: null,
  model: null,
});

const uploadRule = ref({
  folderId: [{ required: true, message: "请选择文件夹", trigger: "change" }],
  name: [{ required: true, message: "请输入模型名称", trigger: "blur" }],
  preview: [{ required: true, message: "请上传预览图", trigger: "change" }],
  model: [{ required: true, message: "请上传模型文件", trigger: "change" }],
});

const handlePreviewChange = (file) => {
  const reader = new FileReader();
  // 监听读取完成事件
  reader.onload = (e) => {
    // 获取文件的 Base64 编码
    const base64String = e.target.result;
    // 将 Base64 字符串存储到 previewUrl 中，用于图片预览
    previewUrl.value = base64String;
    // 将原始文件对象存储到 uploadForm 中
    uploadForm.value.preview = base64String;
  };
  // 读取文件为 Base64 字符串
  reader.readAsDataURL(file.raw);
};

const handleScreenshot = async () => {
  const image = await getViewportImage(
    document.querySelector("#preview-container canvas")
  );
  console.log(document.querySelector("#preview-container canvas"));
  console.log(image.src);
  previewUrl.value = image.src;
  // console.log(image);
  // return image ? image.src : null;
};

// 清理函数
const cleanupPreview = () => {
  if (modelViewer) {
    modelViewer.dispose();
    modelViewer = null;
  }
  if (previewEditor) {
    // 清理编辑器实例
    previewEditor = null;
  }
  if (previewLoader) {
    // 清理加载器实例
    previewLoader = null;
  }
  previewRef.value.innerHTML = "";
};

const timeId = ref(null);
// 上传模型
const handleModelChange = (file, files) => {
  const allowedExtensions = [".gltf", ".glb", ".fbx", ".obj"];
  const extension = file.name.toLowerCase().substr(file.name.lastIndexOf("."));
  if (!allowedExtensions.includes(extension)) {
    ElMessage.warning(
      "不支持的文件类型，请上传 .gltf、.glb、.fbx 或 .obj 文件"
    );
    uploadForm.value.model = null;
    modelFile.value = [];
    return;
  }

  const maxSize = 5 * 1024 * 1024;
  if (file.size > maxSize) {
    ElMessage.warning("文件大小超过限制，请上传小于 5MB 的文件");
    uploadForm.value.model = null;
    modelFile.value = [];
    return;
  }

  if (timeId.value) {
    clearInterval(timeId.value);
    timeId.value = null;
  }

  try {
    modelLoading.value = true;
    const loadingCover = ElLoading.service({
      target: previewRef.value,
      // fullscreen: true,
      text: "模型加载中...",
      background: "rgba(0, 0, 0, 0.7)",
    });

    const reader = new FileReader();

    reader.onload = (e) => {
      try {
        const arrayBuffer = e.target.result;
        const uint8Array = new Uint8Array(arrayBuffer);
        modelFile.value = [
          {
            name: file.name,
            type: file.type,
            size: file.size,
            lastModified: file.lastModified,
            data: Array.from(uint8Array), // 转换为普通数组以便存储
          },
        ];
        uploadForm.value.model = modelFile.value[0];

        // 模型上传后再右侧的preview-container中显示
        const container = previewRef.value;
        if (container) {
          // if (modelViewer) {
          //   modelViewer.reset();
          // }
          // if (!previewEditor) {
          //   // 清理编辑器实例
          //   previewEditor = new EditorPreview();
          // }
          // if (!modelViewer) {
          //   // 创建全新的实例
          //   modelViewer = new Viewport(container, previewEditor);
          // }

          // if (!previewLoader) {
          //   previewLoader = new LoaderPreview(previewEditor);
          // }
          cleanupPreview();
          previewEditor = new EditorPreview();
          modelViewer = new Viewport(container, previewEditor);
          previewLoader = new LoaderPreview(previewEditor);

          previewLoader.loadFiles([file.raw], undefined, async () => {
            await nextTick();

            // if (uploadForm.value.preview && previewUrl.value) {
            //   return;
            // }

            timeId.value = setInterval(() => {
              if (!!previewEditor.selected) {
                clearInterval(timeId.value);
                timeId.value = null;
                // 确保 canvas 元素存在后再获取
                const canvas = document.querySelector(
                  "#preview-container canvas:first-child"
                );
                console.log(canvas);
                if (canvas) {
                  loadingCover.close();
                  // 触发场景更新
                  useDispatchSignal("uploadPreviewSceneGraphChanged");
                  getViewportImage(canvas)
                    .then((image) => {
                      previewUrl.value = image.src;
                      uploadForm.value.preview = image.src;
                    })
                    .catch((error) => {
                      console.error("获取预览图像失败: ", error);
                    });
                }
              }
            }, 500);

            modelLoading.value = false;

            /*

            modelViewer.modules.controls.addEventListener("rest", () => {
              console.log("------------------");
            });

            setTimeout(() => {
              modelLoading.value = false;
              useDispatchSignal("uploadPreviewSceneGraphChanged");
              modelViewer.modules.controls.addEventListener("rest", () => {
                console.log("------------------");
              });
              // 确保 canvas 元素存在后再获取
              const canvas = document.querySelector(
                "#preview-container canvas:first-child"
              );
              console.log(canvas);
              if (canvas) {
                getViewportImage(canvas)
                  .then((image) => {
                    previewUrl.value = image.src;
                    uploadForm.value.preview = image.src;
                  })
                  .catch((error) => {
                    console.error("获取预览图像失败: ", error);
                  });
              }
            }, 1500);
            */
          });
        }
      } catch (error) {
        console.error("处理文件预览时发生错误: ", error);
        if (timeId.value) {
          clearInterval(timeId.value);
          timeId.value = null;
        }
        loadingCover.close();
        modelLoading.value = false; // 确保加载状态被重置
      }
    };
    reader.readAsArrayBuffer(file.raw);
  } catch (error) {
    console.error("文件读取过程中发生错误: ", error);
    modelLoading.value = false; // 确保加载状态被重置
    loadingCover.close();
  }
};

// 移除模型
const handleModelRemove = () => {
  uploadForm.value.model = null;
  modelFile.value = [];
  // uploadForm.value.model = null;
  // modelFile.value = null;
  // previewUrl.value = "";
  // if (modelViewer.value) {
  //   modelViewer.value.reset();
  //   modelViewer.value = null;
  // }
};

const handleExceed = (files) => {
  uploadModelRef.value?.clearFiles();
  const file = files[0];
  uploadModelRef.value?.handleStart(file);
};

const handleUploadClose = () => {
  cleanupPreview();
  // 在清理实例后，移除所有 canvas 元素
  // if (previewRef.value) {
  //   const canvases = previewRef.value.querySelectorAll("canvas");
  //   canvases.forEach((canvas) => canvas.remove());
  // }
  uploadFormRef.value?.resetFields();
  uploadForm.value = {
    folderId: "",
    id: "",
    name: "",
    preview: null,
    model: null,
  };
  isEditModel.value = false;
  editingModelItem.value = null;
  uploadFormRef.value?.clearValidate();
  previewUrl.value = "";
  modelFile.value = [];
  uploadDialogVisible.value = false;
};
// 添加模型到文件夹
const addModelToFolder = async (folderId, modelData) => {
  const folder = folderStructure.value.find((f) => f.id === folderId);
  if (folder) {
    // 检查文件夹中是否已存在同名模型

    // 将 File 对象转换为可序列化的格式
    const fileData =
      modelData.model instanceof File
        ? {
            name: modelData.model.name,
            type: modelData.model.type,
            lastModified: modelData.model.lastModified,
            // 使用 FileReader 读取文件内容
            data: await new Promise((resolve) => {
              const reader = new FileReader();
              reader.onload = () => {
                const arrayBuffer = reader.result;
                const uint8Array = new Uint8Array(arrayBuffer);
                resolve(Array.from(uint8Array));
              };
              reader.readAsArrayBuffer(modelData.model);
            }),
          }
        : modelData.model;

    const serializedModelData = {
      ...modelData,
      model: fileData,
    };

    const existingModelIndex = folder.models.findIndex(
      (m) => m.id === serializedModelData.id
    );
    console.log(existingModelIndex);
    console.log(folder.models[existingModelIndex]);
    if (existingModelIndex != -1) {
      ElMessage.warning("文件夹中已存在同名模型");
      console.log(serializedModelData);
      //直接替换旧模型数据
      folder.models.splice(existingModelIndex, 1, serializedModelData);
    } else {
      folder.models.push(serializedModelData);
    }

    // const rawData = toRaw(folderStructure.value);
    const plainData = JSON.parse(JSON.stringify(folderStructure.value));
    // 存储纯数据对象
    dbStorage.setOtherItem("folderStructure", plainData);
  }
};
const handleUploadConfirm = async () => {
  if (!uploadFormRef.value) return;

  try {
    loading.value = true;
    const valid = await uploadFormRef.value.validate();
    if (valid) {
      //处理文件上传逻辑
      const folder = folderStructure.value.find(
        (f) => f.id === uploadForm.value.folderId
      );

      if (folder) {
        const modelData = {
          id: isEditModel.value ? uploadForm.value.id : Date.now().toString(),
          name: uploadForm.value.name,
          preview: uploadForm.value.preview,
          model: uploadForm.value.model,
        };
        console.log(modelData);
        addModelToFolder(folder.id, modelData);
      }

      handleUploadClose();
    }
  } catch (error) {
    console.error("上传失败:", error);
  } finally {
    loading.value = false;
    // handleUploadClose();
  }
};

/* 右键菜单 */
const contextmenuRef = ref();
const contextmenuOptions = [
  {
    label: "编辑",
    key: "edit",
  },
  {
    label: "删除",
    key: "delete",
  },
];

// 编辑相关的响应式变量
const isEditModel = ref(false);
const editingModelItem = ref(null);

// 场景树节点点击事件，主要用于配合右键菜单
const handleContextmenu = (e, folder, item) => {
  e.preventDefault();
  contextmenuRef.value?.show(e.clientX, e.clientY);
  editingFolderId.value = folder.id;
  editingModelItem.value = item;
  console.log(item);
};

const handleContextmenuSelect = async (key) => {
  if (!editingModelItem.value) return;
  switch (key) {
    case "edit":
      isEditModel.value = true;
      handleAddButtonClick(editingFolderId.value);
      Object.keys(uploadForm.value).forEach((key) => {
        //如果editingModelItem.value中的key,uploadForm.value中也存在, 则赋值
        if (editingModelItem.value.hasOwnProperty(key)) {
          uploadForm.value[key] = editingModelItem.value[key];
        }
      });
      previewUrl.value = uploadForm.value.preview;
      await nextTick();
      // 将耗时操作放在 setTimeout 中
      setTimeout(() => {
        modelFile.value = [
          {
            name: editingModelItem.value.model?.name,
            type: editingModelItem.value.model?.type,
            size: editingModelItem.value.model?.size,
            lastModified: editingModelItem.value.model?.lastModified,
            data: editingModelItem.value.model?.data,
          },
        ];
        initPreviewData(editingModelItem.value);
      }, 0);
      break;
    case "delete":
      ElMessageBox.confirm("确定要删除该模型吗？删除后将无法恢复", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        //找到对应模型的文件夹
        const folder = folderStructure.value.find(
          (f) => f.id === editingFolderId.value
        );
        if (folder) {
          //找到对应模型的索引
          const index = folder.models.findIndex(
            (m) => m.id === editingModelItem.value.id
          );
          if (index !== -1) {
            folder.models.splice(index, 1);
            // 存储纯数据对象
            const plainData = JSON.parse(JSON.stringify(folderStructure.value));
            await dbStorage.setOtherItem("folderStructure", plainData);
            ElMessage.success("删除成功");
          }
        }
      });

      break;
  }
};
//编辑回显
const initPreviewData = async (modelData) => {
  if (!modelData?.model?.data) return;

  const uint8Array = new Uint8Array(modelData.model?.data);
  const blob = new Blob([uint8Array], {
    type: modelData.model?.type,
  });
  const file = new File([blob], modelData.model?.name, {
    type: modelData.model?.type,
    lastModified: modelData.model?.lastModified,
  });

  const container = previewRef.value;
  if (!container) return;

  cleanupPreview();

  // 创建全新的实例
  previewEditor = new EditorPreview();
  modelViewer = new Viewport(container, previewEditor);
  previewLoader = new LoaderPreview(previewEditor);

  previewLoader.loadFiles([file], undefined, async () => {
    console.log("预览加载完成");
  });
};

const addCustomToScene = (modelData) => {
  if (modelData.model && modelData.model.data) {
    // 将存储的数据转回 File 对象
    const uint8Array = new Uint8Array(modelData.model.data);
    const blob = new Blob([uint8Array], { type: modelData.model.type });
    const file = new File([blob], modelData.model.name, {
      type: modelData.model.type,
      lastModified: modelData.model.lastModified,
    });

    // 使用重建的 File 对象加载模型
    window.editor.loader.loadFiles([file], undefined, () => {
      // 加载完成的回调
      // useDispatchSignal("objectSelected", window.editor.selected);
    });
  }
};

let customObject3D = new CustomObject3D();

// 开始拖拽事件
const dragStore = useDragStore();

function dragCustomStart(e, item) {
  dragStore.setData(item);
}

function dragCustomEnd() {
  if (
    dragStore.getActionTarget !== "addToScene" ||
    dragStore.endArea !== "Scene"
  )
    return;

  const position = screenToWorld(
    dragStore.endPosition.x,
    dragStore.endPosition.y
  );
  const modelData = dragStore.getData;
  if (modelData.model && modelData.model?.data) {
    // 将存储的数据转回 File 对象
    const uint8Array = new Uint8Array(modelData.model?.data);
    const blob = new Blob([uint8Array], { type: modelData.model?.type });
    const file = new File([blob], modelData.model?.name, {
      type: modelData.file?.type,
      lastModified: modelData.model?.lastModified,
    });

    // 使用重建的 File 对象加载模型
    window.editor.loader.loadFiles([file], undefined, () => {
      // 加载完成的回调
    });
  }

  // customObject3D.init(dragStore.getData, { position: position });
  dragStore.setActionTarget("");
}
</script>

<style scoped lang="less">
#assets-library-object3dcustom {
  overflow-x: hidden;

  .list {
  }
  .create-new-folder {
    cursor: pointer;
  }
  .hover-container {
    position: relative;
    &:hover {
      background-color: #f5f7fa;
      .operation-buttons {
        display: flex;
      }
    }
  }
  .operation-buttons {
    display: none;
    position: absolute;
    right: 10px;
    gap: 10px;
    align-items: center;
    .el-icon {
      cursor: pointer;
      transition: all 0.3s;
      &:hover {
        transform: scale(1.1);
      }
    }
  }

  .cards {
    padding: 0 10px 10px;
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-gap: 10px 8px;
  }

  .n-card {
    cursor: pointer;

    .n-image {
      display: block;
    }

    :deep(.n-card-cover) {
      img {
        height: 85px;
      }
    }

    :deep(.n-card__content) {
      padding: 3px 0;
      font-size: 13px;
      text-align: center;
    }
  }
}

.upload-dialog-content {
  .form-view {
    flex: 8;
  }
  .preview-view {
    flex: 6;
  }
}

.upload-preview {
  width: 120px;
  height: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  &:hover {
    border-color: #409eff;
  }

  .preview-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .upload-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

.selected-file {
  margin-top: 8px;
  font-size: 14px;
  color: #606266;
}

.el-upload__tip {
  font-size: 12px;
  color: #606266;
  margin-top: 8px;
}
</style>
